import React, { useEffect, useRef } from "react";
import * as echarts from 'echarts';

const Chart4: React.FC = () => {
  const chartRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (chartRef.current) {
      const chart = echarts.init(chartRef.current);
      const option = {
        tooltip: {
          // trigger: 'axis',
          trigger: 'item',
          axisPointer: {
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'            
          }
        },
        legend: {
          data: ['降雨量'],
          // top: 30,
          textStyle: {
            color: '#fff',
            fontSize: 10 // 缩小字体大小
          }
        },
        grid: {
          left: '5%',  // 增加左边距
          right: '5%', // 增加右边距
          bottom: '10%',
          containLabel: true          
        },
        xAxis: [
          {
            type: 'category',
            data: ['今天', '周二', '周三', '周四', '周五', '周六', '周日'],
            axisTick: {
              alignWithLabel: true
            },
            axisLabel: {
              color: '#fff',
              fontSize: 9 // 缩小字体大小
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              color: '#fff',
              fontSize: 10 // 缩小字体大小
            }
          }
        ],
        series: [
          {
            name: '降雨量',
            // 添加标题文本
            label: {
              show: true,
              position: 'top',
              color: '#fff',
              fontSize: 14 // 缩小字体大小
            },
            type: 'bar',
            barWidth: '40%', // 增加图表的宽度
            data: [30, 15, 20, 70, 110, 130,100],
            itemStyle: {
              color: '#5087ec'
            }
          },
        ]
      };
      chart.setOption(option);

      // 窗口调整大小处理
      const handleResize = () => {
        chart.resize();
      };
      window.addEventListener('resize', handleResize);

      return () => {
        window.removeEventListener('resize', handleResize);
        chart.dispose();
      };
    }
  }, []);

  return (
    <>
      <div style={{
        backgroundColor: '#0f1c30',
        width: '100%',
        height: '30vh',
      }} >
        <p style={{
          textAlign: 'center',
          fontSize: '1rem',
          fontWeight: 'bold',
          color: '#fff',
        }} >天气信息</p>
        <div ref={chartRef} style={{ width: '100%', height: '24vh' }}></div>
      </div>
    </>
  );
};

export default Chart4;